const host = 'http://localhost:6000';

// 向content-script主动发送消息
function sendMessageToContentScript(message, callback){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message, function(response) {
            if(callback) callback(response);
        });
    });
}

// 监听来自content-script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    const tabId = sender.id;
    switch(request.cmd){
        case 'tmall':
            $.ajax({
                url: `${host}/pinduoduo/tmallPics`,
                type: 'POST',
                data: request.data,
                success(res, status){
                    sendMessageToContentScript({
                        cmd: 'tmall',
                        data: status === 'success' ? res : res
                    })
                },
                error(res, status){
                    if(status === 'error'){
                        sendMessageToContentScript({
                            cmd: 'tmall',
                            errMsg: '后台服务未开启!'
                        })
                    }
                }
            })
            break;
        case 'single':
            $.ajax({
                url: `${host}/pinduoduo/singleMain`,
                type: 'POST',
                data: request.data,
                success(res, status){
                    if(status === 'success'){
                        alert(`图片成功保存至 ${res.data.path}`);
                    }else{
                        alert(res.errMsg);
                    }
                    sendResponse(res, status);
                }
            })
            break;
        default:
            break;
    }
});